<template>
  <el-table :data="rankPlanData" style="width: 100%">
    <el-table-column type="index" :index="indexMethod" label="序号" width="60%"/>
    <el-table-column label="计划名称" prop="name" />
    <el-table-column label="计划类型" prop="type" />
    <el-table-column label="计划价格" prop="price" />
    <el-table-column label="计划时长" prop="time" />
    <el-table-column label="计划状态" prop="status" />
    <el-table-column fixed="right" label="操作">
      <template #default="props">
        <el-button link type="primary" size="small" @click="openEditDialog(props.row.ID)">编辑</el-button>
        <el-button link type="primary" size="small" @click="delRankPlan(props.row.ID,props.row.name)">删除</el-button>
      </template>
    </el-table-column>

  </el-table>
  <el-dialog v-model="edit_items" title="编辑" width="800">
    <edit_card :ID="edit_ID" @close-dialog="closeEditDialog"></edit_card>
  </el-dialog>

</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import Edit_card from "@/items/rank_plan_items/edit_card.vue";
import {ElMessage} from "element-plus";
import router from "@/router";

interface rank {
  ID: string,
  RID: string,
  name: string,
  type: string,
  price: string,
  time:string,
  status: string
}

const rankPlanData = ref<rank[]>([]);

const edit_items = ref(false);
const edit_ID = ref('');
const fetchrankPlanData = async () => {
  try {
    const formData = new FormData();
    formData.append('key', localStorage.getItem('key'));
    /*const response = await fetch('https://movie.cpb2013.top/admin/account.php?mode=show');*/
    const response = await fetch('https://movie.cpb2013.top/admin/rank.php?mode=query', {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    });
    const responseData = await response.json();
    if (responseData.status === 'success') {
      rankPlanData.value = responseData.data.map((data: any) => ({
        ID: data.ID,
        RID: data.RID,
        name: data.name,
        type: data.type,
        price: data.price,
        time:convertMins(data.time),
        status: data.status,
      }));
    }else if (responseData.status === 'danger') {
      localStorage.removeItem('key');
      ElMessage.error(responseData.msg);
      await router.push('/login'); // Use router to navigate to the login page
    } else {
      console.error('Error fetching movie data:', responseData.message);
    }
  } catch (error) {
    console.error('Error fetching movie data:', error);
  }
}

const indexMethod = (index: number) => {
  return index+1
}

const openEditDialog = (ID) => {
  edit_ID.value = ID;
  edit_items.value = true;
  // console.log(edit_ID.value)
}

const closeEditDialog = () => {
  edit_items.value = false;
  fetchrankPlanData();
}

const delRankPlan = async (ID,name) => {
  // let loading = openFullScreen();
  const formData = new FormData()

  formData.append('ID', ID); // 直接添加 form.type 的值
  formData.append('name', name); // 直接添加 form.type 的值
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch("https://movie.cpb2013.top/admin/rank.php?mode=remove_plan", {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] ==='success')
      {
        ElMessage.success('删除成功！')
        await fetchrankPlanData();
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
      else
      {
        ElMessage.error(result['msg'])
      }
    } else {
      ElMessage.error('删除失败！')
    }
  } catch (error) {
    ElMessage.error('请求失败！')
  }
  // closeFullScreen(loading)
}

const convertMins = (seconds) =>{
  const days = Math.floor(seconds / (24 * 60));
  if (days >= 365) {
    const years = Math.floor(days / 365);
    return `${years}年`;
  } else if (days >= 30) {
    const months = Math.floor(days / 30);
    return `${months}个月`;
  } else {
    return `${days}天`;
  }
}

onMounted(() => {
  fetchrankPlanData();
});
</script>
